package prototype.deepClone;

import java.io.*;

/**
 * @program: DesignModeProject
 * @description:
 * @author: Li canzhang
 * @create: 2022-05-15 10:47
 **/
public class CloneProtoType implements Serializable , Cloneable {
    private static final long serialVersionUID = 3973463906670464120L;
    private String name;
    private DeepCloneTarget deepCloneTarget;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneTarget getDeepCloneTarget() {
        return deepCloneTarget;
    }

    public void setDeepCloneTarget(DeepCloneTarget deepCloneTarget) {
        this.deepCloneTarget = deepCloneTarget;
    }

    //深拷贝  1.重写clone方法
    //引用复杂的话  处理复杂
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //这里完成对基本数据类型的拷贝
        deep = super.clone();
        //对引用类型的拷贝
        CloneProtoType cloneProtoType = (CloneProtoType) deep;
        cloneProtoType.setDeepCloneTarget((DeepCloneTarget)deepCloneTarget.clone());

        return cloneProtoType;
    }

    //深拷贝  2.序列化
    public CloneProtoType deepClone(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //创建流对象
            //序列化操作
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            CloneProtoType copyObj = (CloneProtoType)ois.readObject();
            return copyObj;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
